<template>
  <div class="purchase-detail">
    <el-form
      class="content"
      :model="formData"
      :rules="formRules"
      ref="formDataRef"
      label-width="120px"
    >
      <el-form-item label="集采项目编号" prop="jcProjectCode">
        <el-input
          class="text--info"
          v-model="formData.jcProjectCode"
          placeholder="请输入集采项目编号"
        ></el-input>
      </el-form-item>

      <el-form-item label="集采项目名称" prop="jcProjectName">
        <el-input
          class="text--info"
          v-model="formData.jcProjectName"
          placeholder="请输入集采项目名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="采购方式" prop="proMethodInfo">
        <el-select
          clearable
          filterable
          value-key="dicCode"
          placeholder="请选择采购方式"
          style="width: 100%"
          v-model="formData.proMethodInfo"
        >
          <el-option
            v-for="item in methodList"
            :label="item.dicValue"
            :key="item.dicCode"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="专业方向" prop="professionDirInfo">
        <el-select
          clearable
          filterable
          value-key="dicCode"
          placeholder="请选择专业方向"
          style="width: 100%"
          v-model="formData.professionDirInfo"
        >
          <el-option
            v-for="item in professionList"
            :label="item.dicValue"
            :key="item.dicCode"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="审批预算金额" prop="budgetAmount">
        <el-input
          class="text--info"
          v-model="formData.budgetAmount"
          placeholder="请输入审批预算金额"
        >
          <template #append>万元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="集采负责人" prop="jcLeaderInfo">
        <el-select
          v-model="formData.jcLeaderInfo"
          filterable
          clearable
          remote
          placeholder="请输入集采负责人"
          :remote-method="getUserData"
          value-key="value"
          style="width: 100%"
        >
          <el-option
            v-for="item in userList"
            :key="item.value"
            :label="item.label"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="关联集采方案" prop="purchasSchemeInfo">
        <el-select
          clearable
          filterable
          value-key="dicCode"
          placeholder="请选择关联集采方案"
          style="width: 100%"
          v-model="formData.purchasSchemeInfo"
        >
          <el-option
            v-for="item in purchasSchemeList"
            :label="item.dicValue"
            :key="item.dicCode"
            :value="item"
          />
        </el-select>
      </el-form-item> -->
    </el-form>
    <el-row justify="end" class="form__footer">
      <el-button @click="handleSubmit(false)">取消</el-button>
      <el-button type="primary" @click="handleSubmit(true)">确定</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from "vue";
import { getUserList } from "/@/api/user";
import {
  addCenPurchas,
  updateCenPurchas,
  cenPurchasInfo
} from "/@/api/purchase";
import NotifMessage from "/@/utils/message/notification";
export default defineComponent({
  name: "purchaseDetail",
  props: {
    methodList: {
      type: Array,
      default: () => []
    },
    professionList: {
      type: Array,
      default: () => []
    },
    purId: {
      type: String || Number,
      default: ""
    }
  },
  emits: ["emitClose", "updateClose"],
  setup(props, { emit }) {
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const userList = ref([]);
    const purchasSchemeList = [
      { dicValue: "方案A", dicCode: "A" },
      { dicValue: "方案B", dicCode: "B" }
    ];
    const state = reactive({
      formData: {
        jcProjectCode: "",
        jcProjectName: "",
        budgetAmount: "",
        jcLeaderInfo: "" as any,
        jcLeaderId: "",
        jcLeaderName: "",
        proMethodInfo: "" as any,
        proMethodCode: "",
        proMethodName: "",
        professionDirInfo: "" as any,
        professionDirCode: "",
        professionDirName: "",
        purchasSchemeInfo: "" as any,
        purchasSchemeCode: "",
        purchasSchemeName: ""
      }
    });
    const validateAmount = (rule: any, value: any, callback: any) => {
      if (!value) {
        return callback(new Error("请输入预算金额"));
      } else {
        const reg = /^(([1-9]\d*)|0)(\.\d{1,5})?$/;
        if (!reg.test(value)) {
          return callback(new Error("请输入正确的金额格式"));
        } else {
          callback();
        }
      }
    };
    const formRules = ref({
      jcProjectCode: [
        { required: true, message: "请输入集采项目编号", trigger: "blur" }
      ],
      jcProjectName: [
        { required: true, message: "请输入集采项目名称", trigger: "blur" }
      ],
      proMethodInfo: [
        { required: true, message: "请选择采购方式", trigger: "change" }
      ],
      professionDirInfo: [
        { required: true, message: "请选择专业方式", trigger: "change" }
      ],
      budgetAmount: [
        { required: true, validator: validateAmount, trigger: "blur" }
      ],
      jcLeaderInfo: [
        { required: true, message: "请输入集采负责人", trigger: "change" }
      ]
    });

    // 确认提交
    const handleSubmit = async (isSubmit: boolean) => {
      if (isSubmit) {
        const isValid = await new Promise(resolve =>
          formDataRef.value.validate(resolve)
        );
        if (!isValid) return;
        state.formData.jcLeaderId = state.formData.jcLeaderInfo.value;
        state.formData.jcLeaderName = state.formData.jcLeaderInfo.label;
        state.formData.proMethodCode = state.formData.proMethodInfo.dicCode;
        state.formData.proMethodName = state.formData.proMethodInfo.dicValue;
        state.formData.professionDirCode =
          state.formData.professionDirInfo.dicCode;
        state.formData.professionDirName =
          state.formData.professionDirInfo.dicValue;
        state.formData.purchasSchemeCode =
          state.formData.purchasSchemeInfo.dicCode;
        state.formData.purchasSchemeName =
          state.formData.purchasSchemeInfo.dicValue;
        if (String(props.purId)) {
          updatePurchase();
        } else {
          addPurchase();
        }
      } else {
        emit("emitClose");
      }
    };

    //新增集采项目
    const addPurchase = async () => {
      try {
        const { code, message } = await addCenPurchas(state.formData);
        if (code === 200) {
          NotifMessage.success(message);
          emit("updateClose");
        }
      } catch (err) {
        console.log("error", err);
      }
    };

    //更新集采项目
    const updatePurchase = async () => {
      try {
        const { code, message } = await updateCenPurchas(state.formData);
        if (code === 200) {
          NotifMessage.success(message);
          emit("updateClose");
        }
      } catch (err) {
        console.log("error", err);
      }
    };

    // 获取详情
    const getCenPurchasInfo = async purId => {
      try {
        let postData = { id: purId };
        const { code, data } = await cenPurchasInfo(postData);
        if (code === 200) {
          state.formData = data;
          state.formData.jcLeaderInfo = {
            label: state.formData.jcLeaderName,
            value: state.formData.jcLeaderId
          };
          state.formData.proMethodInfo = {
            dicValue: state.formData.proMethodName,
            dicCode: state.formData.proMethodCode
          };
          state.formData.professionDirInfo = {
            dicValue: state.formData.professionDirName,
            dicCode: state.formData.professionDirCode
          };
          state.formData.purchasSchemeInfo = {
            dicValue: state.formData.purchasSchemeName,
            dicCode: state.formData.purchasSchemeCode
          };
          userList.value = [state.formData.jcLeaderInfo];
        }
      } catch (err) {
        console.log(err);
      }
    };

    //获取项目组成员
    const getUserData = async (query = "") => {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 100,
          nameLike: query
        };
        const { code, data } = await getUserList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return { value: item.id, label: `${item.name}(${item.userName})` };
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    if (String(props.purId)) {
      getCenPurchasInfo(props.purId);
    }

    return {
      ...toRefs(state),
      userList,
      handleSubmit,
      getUserData,
      formRules,
      formDataRef,
      purchasSchemeList
    };
  }
});
</script>
<style lang="scss" scoped>
:deep.purchase-detail {
  .content {
    padding-right: 46px;
  }
}
</style>
